using Common.Communal;
using MediatR;
using Product.API.Read.Applications.Commands.Bom;
using SqlSugar;

namespace Product.API.Read.Applications.CommandHandlers.Bom
{
    /// <summary>
    /// 按BomNumber查询产品用料
    /// </summary>
    public class GetProductMaterialByBomNumberCommandHandler : IRequestHandler<GetProductMaterialByBomNumberCommand, ApiResult<List<ERP.Domain.Products.ProductMaterial>>>
    {
        /// <summary>
        /// SqlSugar
        /// </summary>
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">SqlSugar</param>
        public GetProductMaterialByBomNumberCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        /// <summary>
        /// 处理
        /// </summary>
        public Task<ApiResult<List<ERP.Domain.Products.ProductMaterial>>> Handle(GetProductMaterialByBomNumberCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ERP.Domain.Products.ProductMaterial>> result = new ApiResult<List<ERP.Domain.Products.ProductMaterial>>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            var productNumber = db.Queryable<ERP.Domain.Products.BomInfo>()
                                  .Where(b => b.IsDelete == false && b.BomNumber == request.BomNumber)
                                  .Select(b => b.ProductNumber)
                                  .First();

            var data = db.Queryable<ERP.Domain.Products.ProductMaterial>()
                         .Where(x => x.IsDelete == false && x.ProductNumber == productNumber)
                         .ToList();
            result.Data = data;

            return Task.FromResult(result);
        }
    }
}


